<?php
/*
 * @Descripttion: 人员管理
 * @version: v1
 * @Author: Terry
 * @Date: 2021-10-07 11:14:24
 * @LastEditors: Terry
 * @LastEditTime: 2024-12-17 23:00:12
 */

declare(strict_types=1);

namespace app\certificate\controller\admin\v1\risk;

use Exception;
use libs\ALiOss;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Html2Pdf;
use think\Request;
use think\facade\Db;

class Index
{

  /**
   * @Description: 查看列表
   * @Author: Terry
   * @Date: 2024-02-17 17:44:02
   */
  public function getList(Request $request)
  {
    $data = $request->data;

    $searchWhere = [
      ['rt.projectCode', '=', $request->prjCode],
    ];

    //状态,待审核-0,使用中-1，已过期-2
    if (!empty($data['status']) || (isset($data['status']) && $data['status'] == 0)) {
      if ($data['status'] == 2) {
        array_push($searchWhere, ['r.expiredTime', '<', date('Y-m-d H:i:s')]);
      } else {
        array_push($searchWhere, ['r.status', '=', $data['status']]);
        array_push($searchWhere, ['r.expiredTime', '>', date('Y-m-d H:i:s')]);
      }
    }
    if (!empty($data['workerName'])) array_push($searchWhere, ['wi.name', 'like', "%{$data['workerName']}%"]);
    if (!empty($data['typeUuid'])) array_push($searchWhere, ['r.typeUuid', '=', $data['typeUuid']]);
    if (isset($request->authWhere['corpCode'])) array_push($searchWhere, ['rt.corpCode', '=', $request->authWhere['corpCode']]);
    if (!empty($data['subcontractor'])) array_push($searchWhere, ['r.subcontractor', 'like', "%{$data['subcontractor']}%"]);

    $list = DB::table('certificate_risk')
      ->alias('r')
      ->join('certification_projectWorker wi', 'wi.wxappUserUuid = r.wxappUserUuid', 'left')
      ->join('certificate_riskType rt', 'rt.uuid = r.typeUuid')
      ->join('certificate_area a', 'a.uuid = r.areaUuid', 'left')
      ->join('certification_projectWorker wa', 'wa.wxappUserUuid = r.auditUserUuid', 'left')
      ->where($searchWhere)
      ->page((int)$data['page'], (int)$data['limit'])
      ->field(['rt.name', 'wi.workerName', 'r.inDate', 'r.status', 'r.uuid', 'r.expiredTime', 'r.reason', 'r.subcontractor', 'r.location', 'wa.workerName as auditUserName', 'r.auditTime', 'a.name as areaName'])
      ->order('r.id desc')
      ->distinct(true)
      ->select()->toArray();

    foreach ($list as &$value) {
      if (strtotime($value['expiredTime']) < time()) {
        $value['status'] = '2'; //已过期
      }
    }

    $count = DB::table('certificate_risk')
      ->alias('r')
      ->join('certification_projectWorker wi', 'wi.wxappUserUuid = r.wxappUserUuid')
      ->join('certificate_riskType rt', 'rt.uuid = r.typeUuid')
      ->join('certificate_area a', 'a.uuid = r.areaUuid', 'left')
      ->join('certification_projectWorker wa', 'wa.wxappUserUuid = r.auditUserUuid', 'left')
      ->where($searchWhere)
      ->distinct(true)
      ->count();

    $data  =  compact('list', 'count');
    return result(SUCCESS, $data, '');
  }
  /**
   * @Description: 
   * @Author: Terry
   * @Date: 2024-02-21 21:28:19
   */
  public function getDetail(Request $request)
  {
    $data = $request->data;

    $data = DB::table('certificate_risk')
      ->alias('r')
      // ->join('certification_workerInfo wi', 'wi.wxappUserUuid = r.wxappUserUuid')
      ->join('certificate_riskType rt', 'rt.uuid = r.typeUuid')
      ->join('certificate_area a', 'a.uuid = r.areaUuid', 'left')
      // ->join('platform_corpBasicInfo cbi', 'cbi.corpCode = rt.corpCode')
      ->where('r.uuid', $data['uuid'])
      // ->field(['r.formData', 'rt.name', 'wi.name as workerName', 'r.inDate', 'r.status', 'r.uuid', 'r.expiredTime', 'r.reason', 'r.subcontractor', 'r.location', 'r.auditUserName', 'r.auditTime', 'a.name as areaName'])
      ->field(['rt.name', 'rt.subtitle', 'r.expiredTime', 'r.subcontractor', 'r.formData',"CONCAT(a.name,'-',r.location) as location"])
      ->find();
    if (!$data) return result(FAIL, [], '数据有误请重试');

    $data['formData'] = json_decode(html_entity_decode($data['formData']), true);

    foreach ($data['formData'] as $key => &$value) {
      if ($value['tag'] == 'signature') {
        $data['signature'][] = $value;
        unset($data['formData'][$key]);
      }
    }

    //已過期
    if (strtotime($data['expiredTime']) < time()) $data['status'] = '2';

    return result(SUCCESS, $data, '');
  }

  /**
   * @Description: 获取人员数据
   * @Author: Terry
   * @Date: 2024-06-14 16:45:34
   * @param {Request} $request
   */
  public function getWorker(Request $request)
  {
    $data = $request->data;

    $where = [
      ['projectCode', '=', $request->prjCode],
      ['isDelete', '=', 0],
    ];
    if (!empty($request->authWhere['corpCode'])) array_push($where, ['corpCode', '=', $request->corpCode]);

    $attendanceWhere = [
      ['entryTime', '<>', '0000-00-00 00:00:00'],
      ['exitTime', '=', '0000-00-00 00:00:00'],
    ];

    $list = DB::table('certification_projectWorker')
      ->where(array_merge($where, $attendanceWhere))
      ->field(['teamName', 'workerName', 'teamSysNo', 'wxappUserUuid', 'corpName', 'corpCode'])
      ->group(['wxappUserUuid', 'corpCode'])
      ->select()->toArray();

    foreach ($list as $key => $value) {
      if (empty($value['workerName'])) {
        $list[$key]['workerName'] = DB::table('platform_wxappUser')->where('wxappUserUuid', $value['wxappUserUuid'])->value('nickName');
      }
    }
    $list = $this->centerProcess($list);

    $checked = DB::table('certificate_riskWorker')
      ->where(['riskUuid' => $data['uuid'], 'isDelete' => 0])
      ->column('wxappUserUuid');

    $data = compact('list', 'checked');

    return result(SUCCESS, $data, '');
  }

  /**
   * @Description: 修改相关人员
   * @Author: Terry
   * @Date: 2024-06-14 16:46:14
   * @param {Request} $request
   */
  public function changeWorker(Request $request)
  {
    $data = $request->data;
    $riskUuid = $data['uuid'];

    $globalData = dataMerge($request->uuid, [
      'riskUuid' => $riskUuid,
    ]);
    $where   = [
      'riskUuid' => $riskUuid,
      'isDelete' => 0,
    ];


    $check = DB::table('certificate_risk')->where(['uuid' => $data['uuid'], 'isDelete' => 0])->field(['expiredTime', 'exitTime'])->find();
    if ($check['exitTime'] != '0000-00-00 00:00:00') return result(FAIL, '', '已注銷，無法修改');
    if (strtotime($check['expiredTime']) < time()) return result(FAIL, '', '已過期，無法修改');

    $oldData =  DB::table('certificate_riskWorker')
      ->where(['riskUuid' => $data['uuid'], 'isDelete' => 0])
      ->column('wxappUserUuid');
    $newData =  array_column($data['value'], 'wxappUserUuid');
    $create = array_diff($newData, $oldData);
    $delete = array_diff($oldData, $newData);

    DB::startTrans();
    try {
      if ($create) {
        foreach ($create as $key => $value) {
          $insertData[] = array_merge(['wxappUserUuid' => $value, 'uuid' => createUuid()], $globalData);
        }
        DB::table('certificate_riskWorker')->insertAll($insertData);
      }
      if ($delete) {
        DB::table('certificate_riskWorker')
          ->where([
            'wxappUserUuid' => $delete,
            'riskUuid' => $riskUuid,
          ])
          ->update(['isDelete' => 1]);
      }
      DB::commit();
      return result(SUCCESS, '', '更新成功');
    } catch (\Exception $e) {
      // 回滚事务
      DB::rollback();
      return result(FAIL, '', '更新失败');
    }
  }

  //人员分类信息     
  private function centerProcess($data)
  {
    if (!$data) return $data;
    $arr = [];
    foreach ($data as $key => $value) {
      if (empty($value['workerName'])) {
        $wxappUserData = DB::table('platform_wxappUser')->where('wxappUserUuid', $value['value'])->field(['nickName'])->findOrEmpty();
        if (empty($wxappUserData)) continue;
        $value['workerName'] = $wxappUserData['nickName'];
        $value['hasWorkerInfo'] = 0;
      }
      $data = [
        'value' => $value['wxappUserUuid'],
        'name' => $value['workerName'],
        'corpCode' => $value['corpCode'],
      ];
      $arr[$value['corpCode']]['name'] = $value['corpName'];
      $arr[$value['corpCode']]['children'][$value['teamSysNo']]['name'] = $value['teamName'];
      $arr[$value['corpCode']]['children'][$value['teamSysNo']]['children'][] = $data;
    }
    sort($arr);
    foreach ($arr as $key => $value) {
      if (isset($value['children'])) {
        sort($value['children']);
        $arr[$key]['children'] = $value['children'];
      }
    }
    return $arr;
  }

  /**
   * @Description: 获取字典
   * @Author: Terry
   * @Date: 2024-02-17 17:36:06
   * @param {Request} $request
   */
  public function getOptions(Request $request)
  {
    $where = [
      ['projectCode', '=', $request->authWhere['projectCode']],
      // ['isDelete','=','0'],
    ];
    //判断身份
    if (isset($request->authWhere['corpCode'])) {
      array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
    }

    $data =  DB::table('certificate_riskType')
      ->where($where)
      ->order(['id desc'])
      ->field(['name', 'uuid'])
      ->select()->toArray();

    return result(SUCCESS, $data, '');
  }

  /**
   * @Description: 人员移除
   * @Author: Terry
   * @Date: 2024-02-20 16:20:56
   */
  public function destroy(Request $request)
  {
    $data = $request->data;
    DB::startTrans();
    try {
      $updateRes = DB::table('certificate_workerAssociation')->whereIn('uuid', $data['uuid'])->update(['isDelete' => 1]);
      $association = DB::table('certificate_workerAssociation')->whereIn('uuid', $data['uuid'])->field(['wxappUserUuid', 'workerUuid'])->select();
      foreach ($association as $key => $value) {
        $updateRes = DB::table('certificate_workerItemSubmit')
          ->where([
            'workerUuid' => $value['workerUuid'],
            'wxappUserUuid' => $value['wxappUserUuid'],
          ])
          ->update(['isDelete' => 1]);
      }
      DB::commit();
      return result(SUCCESS, '', '移除成功');
    } catch (\Exception $e) {
      // 回滚事务
      DB::rollback();
    }
    return result(FAIL, '', '移除失败,请重试');
  }

  /**
   * html转pdf
   *
   * @param Request $request
   * @return void
   */
  public function html2Pdf(Request $request)
  {
    $data     = $request->data;
    $uuid     = $data['uuid']; //许可证唯一码
    try {
      $info = DB::table('certificate_risk')
        ->alias('r')
        ->join('certificate_riskType rt', 'rt.uuid = r.typeUuid')
        ->where('r.uuid', $uuid)
        ->find();
      if (!$info) return result(FAIL, [], '数据有误请重试');
      if($info['status'] != 1) return result(FAIL, [], '许可证未审核通过');

      $exec = exec('whereis wkhtmltopdf', $oupput, $result_code);
      if (!$exec) {
        return result(FAIL, '', 'wkhtmltopdf工具未安装,请联系管理员');
      }
      $domain = request()->domain();
      $url = $domain . "/api/certificate/admin/v1/risk/index/pdf?uuid={$uuid}";

      $path2 = 'uploads/' . time() . '.pdf';
      $path = root_path() . '/public/' . $path2;

      // 获取文件的目录路径
      $dir = dirname($path);
      // 判断目录是否存在
      if (!is_dir($dir)) {
        // 如果目录不存在，则创建目录
        if (!mkdir($dir, 0777, true)) {
          // 如果创建失败，可以抛出错误或处理异常
          return result(FAIL, '', '创建目录失败');
        }
      }
      $token = $_SERVER["HTTP_AUTHORIZATION"];
      $userUuid = $_SERVER["HTTP_UUID"];
      // 执行 wkhtmltopdf 命令
      $command = "wkhtmltopdf " .
        "--custom-header 'Authorization' {$token} " .
        "--custom-header 'uuid' {$userUuid} " .
        "--custom-header 'corpCode' {$request->corpCode} " .
        "--custom-header 'puuid' {$request->prjCode} " .
        "{$url} {$path}";
      exec($command . ' 2>&1', $output, $result_code);
      // if ($result_code !== 0) {
      //   return result(FAIL, '', implode(',', $output));
      // }
      if (file_exists($path) == false) {
        return result(FAIL, '', '导出pdf失败');
      }
      $exp = explode('.', $path2);
      $oss = new ALiOss($exp[0], $exp[1]);
      $ossPath = $oss->upload($path2);
      @unlink($path);
      return result(SUCCESS, ['path' => $ossPath], '导出路径');
    } catch (Exception $e) {
      return result(FAIL, '', $e->getMessage()());
    }
  }

  public function pdf(Request $request)
  {
    $data = $request->data;
    $data = DB::table('certificate_risk')
      ->alias('r')
      ->join('certificate_riskType rt', 'rt.uuid = r.typeUuid')
      ->where('r.uuid', $data['uuid'])
      ->field(['rt.name', 'rt.subtitle', 'r.expiredTime', 'r.subcontractor', 'r.location', 'r.formData'])
      ->find();
    if (!$data) return result(FAIL, [], '数据有误请重试');
    $data['formData'] = json_decode(html_entity_decode($data['formData']), true);
    foreach ($data['formData'] as $key => &$value) {
      if ($value['tag'] == 'signature') {
        $data['signature'][] = $value;
        unset($data['formData'][$key]);
      }
    }
    //已過期
    if (strtotime($data['expiredTime']) < time()) $data['status'] = '2';

    return view('', ['data' => $data]);
  }
    /**
   * @Description: 
   * @Author: Terry
   * @Date: 2024-02-21 21:28:19
   */
  public function pdfPage(Request $request)
  {
    $data = $request->get();
    $data = DB::table('certificate_risk')
      ->alias('r')
      ->join('certificate_riskType rt', 'rt.uuid = r.typeUuid')
      ->where('r.uuid', $data['uuid'])
      ->field(['rt.name', 'rt.subtitle', 'r.expiredTime', 'r.subcontractor', 'r.location', 'r.formData'])
      ->find();
    if (!$data) return result(FAIL, [], '数据有误请重试');

    $formData = json_decode(html_entity_decode($data['formData']), true);
    foreach ($formData as &$value) {
      $value = [
        'label'=>$value['label'],
        'image'=>$value['image'],
        'tag'=>$value['tag'],
        'subtitle'=>$value['subtitle'],
        'defaultValue'=>$value['defaultValue'],
        'options'=>$value['options'] ?? [],
      ];
    }
    foreach ($formData as $key => &$value) {
      if ($value['tag'] == 'signature') {
        $data['signature'][] = $value;
        unset($formData[$key]);
      }
    }
   
    foreach ($formData as $key => $value) {
        
    }  
    dd($finalArray);

    //已過期
    if (strtotime($data['expiredTime']) < time()) $data['status'] = '2';

    // return result(SUCCESS, $data, '');
  }
}
